//
//  CommonTools.h
//
//  Created by ttouch on 17/10/8.
//  Copyright © 2017年 肖兰月. All rights reserved.
//

#import "CommonTools.h"
#import "math.h"

@implementation CommonTools

#pragma mark - 应用信息
+ (NSString *)appDisplayName {
    NSString *appDisplayName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
    if (!appDisplayName) appDisplayName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
    return appDisplayName;
}

+ (NSString *)appBundleName {
    return [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
}

+ (NSString *)appVersion {
    NSString *version = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    return version;
}

+ (BOOL)needShowNewFeature {
    NSString *lastVersion = [LLUserDefaults objectForKey:@"lastVersion"];
    if (!lastVersion || ![lastVersion isEqualToString:[self appVersion]]) {
        [LLUserDefaults setObject:[self appVersion] forKey:@"lastVersion"];
        [LLUserDefaults synchronize];
        return YES;
    }
    return NO;
}

#pragma mark - 文本计算
/// 计算文字size
+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize {
    return [self sizeOfText:text fontSize:fontSize width:CGFLOAT_MAX height:5000];
}

+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize width:(CGFloat)width {
    return [self sizeOfText:text fontSize:fontSize width:width height:5000];
}

+ (CGSize)sizeOfText:(NSString *)text fontSize:(CGFloat)fontSize width:(CGFloat)width height:(NSInteger)height {
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:LLRegularFont(fontSize)} context:nil].size;
    return size;
}

#pragma mark - 正则验证
+ (BOOL)isNumText:(NSString *)text {
    if ([text stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]].length > 0) {
        return NO;
    }
    return YES;
}

#pragma mark - 是否是身份证
+ (BOOL)validateIdentityCard: (NSString *)identityCard
{
    identityCard = [identityCard stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSInteger length =0;
    if (!identityCard) {
        return NO;
    }else {
        length = identityCard.length;
        //不满足15位和18位，即身份证错误
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray = @[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    // 检测省份身份行政区代码
    NSString *valueStart2 = [identityCard substringToIndex:2];
    BOOL areaFlag =NO; //标识省份代码是否正确
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    if (!areaFlag) {
        return NO;
    }
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    int year =0;
    //分为15位、18位身份证进行校验
    switch (length) {
        case 15:
            //获取年份对应的数字
            year = [identityCard substringWithRange:NSMakeRange(6,2)].intValue +1900;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                //创建正则表达式 NSRegularExpressionCaseInsensitive：不区分字母大小写的模式
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"  options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            //使用正则表达式匹配字符串 NSMatchingReportProgress:找到最长的匹配字符串后调用block回调
            numberofMatch = [regularExpression numberOfMatchesInString:identityCard options:NSMatchingReportProgress range:NSMakeRange(0, identityCard.length)];
            if(numberofMatch >0) {
                return YES;
            }
            else {
                return NO;
            }
        case 18:
            year = [identityCard substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:identityCard options:NSMatchingReportProgress range:NSMakeRange(0, identityCard.length)];
            if(numberofMatch >0) {
                //1：校验码的计算方法 身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为：7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2。将这17位数字和系数相乘的结果相加。
                int S = [identityCard substringWithRange:NSMakeRange(0,1)].intValue*7 + [identityCard substringWithRange:NSMakeRange(10,1)].intValue *7 + [identityCard substringWithRange:NSMakeRange(1,1)].intValue*9 + [identityCard substringWithRange:NSMakeRange(11,1)].intValue *9 + [identityCard substringWithRange:NSMakeRange(2,1)].intValue*10 + [identityCard substringWithRange:NSMakeRange(12,1)].intValue *10 + [identityCard substringWithRange:NSMakeRange(3,1)].intValue*5 + [identityCard substringWithRange:NSMakeRange(13,1)].intValue *5 + [identityCard substringWithRange:NSMakeRange(4,1)].intValue*8 + [identityCard substringWithRange:NSMakeRange(14,1)].intValue *8 + [identityCard substringWithRange:NSMakeRange(5,1)].intValue*4 + [identityCard substringWithRange:NSMakeRange(15,1)].intValue *4 + [identityCard substringWithRange:NSMakeRange(6,1)].intValue*2 + [identityCard substringWithRange:NSMakeRange(16,1)].intValue *2 + [identityCard substringWithRange:NSMakeRange(7,1)].intValue *1 + [identityCard substringWithRange:NSMakeRange(8,1)].intValue *6 + [identityCard substringWithRange:NSMakeRange(9,1)].intValue *3;
                //2：用加出来和除以11，看余数是多少？余数只可能有0－1－2－3－4－5－6－7－8－9－10这11个数字
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 3：获取校验位
                NSString *lastStr = [identityCard substringWithRange:NSMakeRange(17,1)];
                //4：检测ID的校验位
                if ([lastStr isEqualToString:@"x"]) {
                    if ([M isEqualToString:@"X"]) {
                        return YES;
                    }else{
                        return NO;
                    }
                }else{
                    if ([M isEqualToString:[identityCard substringWithRange:NSMakeRange(17,1)]]) {
                        return YES;
                    }else {
                        return NO;
                    }
                }
            }else {
                return NO;
            }
        default:
            return NO;
    }
}

#pragma mark - 是否是手机号
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,183
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,177
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-9]|8[0-9]|7[0-9])\\d{8}$";
    NSString * CM = @"^1(34[0-9]|(3[0-9]|5[0-9]|8[0-9])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09]|77)[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    return (([regextestmobile evaluateWithObject:mobileNum]) || ([regextestcm evaluateWithObject:mobileNum]) || ([regextestct evaluateWithObject:mobileNum]) || ([regextestcu evaluateWithObject:mobileNum]));
}

#pragma mark - 是否是邮箱
+ (BOOL)isEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

#pragma mark - 是否是QQ
+ (BOOL)isQqNumber:(NSString *)qqNum {
    NSString *qqstr = @"[1-9][0-9]{4,}";
    NSPredicate *qqTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",qqstr];
    return [qqTest evaluateWithObject:qqNum];
}

#pragma mark - 是否是银行卡
+ (BOOL)isBankCardNumber: (NSString *)bankCardNumber {
    BOOL flag;
    if (bankCardNumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{15,30})";
    NSPredicate *bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [bankCardPredicate evaluateWithObject:bankCardNumber];
}

#pragma mark - 颜色相关
#pragma mark - 返回随机颜色
+ (UIColor *)colorLightRandom {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 );  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

#pragma mark - 以UIColor生成一张UIImage
+ (UIImage *)imageCreateWithColor:(UIColor *)color {
    return [self imageCreateWithColor:color size:CGSizeMake(1.0, 1.0)];
}

+ (UIImage *)imageCreateWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *)createImageWithColor:(UIColor *)color width:(CGFloat)width {
    CGRect rect = CGRectMake(0.0f, 0.0f, width, width);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark - 图片相关
#pragma mark - 压缩图片尺寸,方便上传服务器
+ (UIImage *)scaleImage:(UIImage *)img size:(CGSize)size {
    if (img.size.width <= size.width) {
        return img;
    }
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return newImage;
}

+ (UIImage *)scaleImage:(UIImage *)image scale:(CGFloat)scale {
    //确定压缩后的size
    CGFloat scaleWidth = image.size.width * scale;
    CGFloat scaleHeight = image.size.height * scale;
    CGSize scaleSize = CGSizeMake(scaleWidth, scaleHeight);
    //开启图形上下文
    UIGraphicsBeginImageContext(scaleSize);
    //绘制图片
    [image drawInRect:CGRectMake(0, 0, scaleWidth, scaleHeight)];
    //从图形上下文获取图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSDictionary *)scaleImage:(UIImage *)image toKByte:(NSInteger)kByte {
    CGFloat compression = 1;
    CGFloat maxLength = kByte * 1024;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return @{@"image":image,@"data":data};
    CGFloat max = 1;
    CGFloat min = 0;
    for (NSInteger i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return @{@"image":resultImage,@"data":data};

    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return @{@"image":resultImage,@"data":data};
}

+ (NSData *)resetSizeOfImageData:(UIImage *)sourceImage maxSize:(NSInteger)maxSize {
    //先判断当前质量是否满足要求，不满足再进行压缩
    __block NSData *finallImageData = UIImageJPEGRepresentation(sourceImage,1.0);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1000;
    
    if (sizeOriginKB <= maxSize) {
        return finallImageData;
    }
    
    //获取原图片宽高比
    CGFloat sourceImageAspectRatio = sourceImage.size.width/sourceImage.size.height;
    //先调整分辨率
    CGSize defaultSize = CGSizeMake(1024, 1024/sourceImageAspectRatio);
    UIImage *newImage = [self newSizeImage:defaultSize image:sourceImage];
    
    finallImageData = UIImageJPEGRepresentation(newImage,1.0);
    
    //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }
    
    /*
     调整大小
     说明：压缩系数数组compressionQualityArr是从大到小存储。
     */
    //思路：使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
    //如果还是未能压缩到指定大小，则进行降分辨率
    while (finallImageData.length == 0) {
        //每次降100分辨率
        CGFloat reduceWidth = 100.0;
        CGFloat reduceHeight = 100.0/sourceImageAspectRatio;
        if (defaultSize.width-reduceWidth <= 0 || defaultSize.height-reduceHeight <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-reduceWidth, defaultSize.height-reduceHeight);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
    }
    return finallImageData;
}

#pragma mark 调整图片分辨率/尺寸（等比例缩放）
+ (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)sourceImage {
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
    } else if (tempHeight > 1.0 && tempWidth < tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark 二分法
+ (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;
    
    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;
        
        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
        
        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
        NSLog(@"当前降到的质量：%ld", (unsigned long)sizeOriginKB);
        NSLog(@"\nstart：%zd\nend：%zd\nindex：%zd\n压缩系数：%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
        
        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}

#pragma mark - 时间戳 <-> 时间字符串 转换
#pragma mark - 时间戳 -> 时间字符串 dateFormat默认为yyyy-MM-dd
+ (NSString *)getTimeStrBytimeStamp:(NSString *)timeStamp {
    return [self getTimeStrBytimeStamp:timeStamp dateFormat:@"yyyy-MM-dd"];
}

+ (NSString *)getTimeStrBytimeStamp:(NSString *)timeStamp dateFormat:(NSString *)dataFormat {
    if (![CommonTools isNotNull:timeStamp]) return @"";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dataFormat];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStamp doubleValue]/1000];
    if (!date) return @"";
    NSString *dateString = [formatter stringFromDate:date];
    return dateString ? dateString : @"";
}

#pragma mark - 时间字符串 -> 时间戳 dateFormat默认为yyyy-MM-dd
+ (NSString *)getTimeStampBytimeStr:(NSString *)timeStr {
    return [self getTimeStampBytimeStr:timeStr dateFormat:@"yyyy-MM-dd"];
}

+ (NSString *)getTimeStampBytimeStr:(NSString *)timeStr dateFormat:(NSString *)dataFormat {
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    formatter.dateFormat = dataFormat;
    NSDate *date = [formatter dateFromString:timeStr];
    NSString *timeSp = [NSString stringWithFormat:@"%.f",[date timeIntervalSince1970]];
    return timeSp;
}

#pragma mark - 富文本字符串处理
#pragma mark - 返回NSAttributedString，左侧String为灰色，右侧为kMainColor
+ (NSAttributedString *)getAttributedStringWithFirstString:(NSString *)firstStr firstColor:(UIColor *)firstColor lastString:(NSString *)lastStr lastColor:(UIColor *)lastColor fontSize:(CGFloat )fontSize {
    UIFont *font = [UIFont fontWithName:@"ZhaimiMedium-" size:fontSize];
    NSMutableAttributedString *p1 = [[NSMutableAttributedString alloc] initWithString:firstStr attributes:@{ NSFontAttributeName : font, NSForegroundColorAttributeName :firstColor }];
    NSMutableAttributedString *p2 = [[NSMutableAttributedString alloc] initWithString:lastStr attributes:@{ NSFontAttributeName : font, NSForegroundColorAttributeName :lastColor }];
    [p1 appendAttributedString:p2];
    return p1;
}

#pragma mark - 距离计算
/*
 2个坐标距离
 常用到如image1.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(335));
 CGAffineTransformMakeRotation中要填的是弧度，所以要转换一下。
 下面是两个宏，来实现互转
 1。弧度转角度
 #define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
 NSLog(@”Output radians as degrees: %f”, RADIANS_TO_DEGREES(0.785398));
 2。角度转弧度
 // Degrees to radians
 #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
 NSLog(@”Output degrees as radians: %f”, DEGREES_TO_RADIANS(45));
 M_PI 定义在Math.h内，其值为3.14159265358979323846264338327950288
 */
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
+ (NSString *)locationWithLatitude:(NSString *)firstLatitude withLongitude:(NSString *)firstLongitude WithLatitude:(NSString *)secondLatitude withLongitude:(NSString *)secondLongitude {
    double firLat = [firstLatitude doubleValue];
    double secLat = [secondLatitude doubleValue];
    double firLng = [firstLongitude doubleValue];
    double secLng = [secondLongitude doubleValue];
    
    double theta = firLng - secLng;
    double miles = (sin(DEGREES_TO_RADIANS(firLat)) * sin(DEGREES_TO_RADIANS(secLat))) + (cos(DEGREES_TO_RADIANS(firLat)) * cos(DEGREES_TO_RADIANS(secLat)) * cos(DEGREES_TO_RADIANS(theta)));
    miles = acos(miles);
    miles = RADIANS_TO_DEGREES(miles);
    miles = miles * 60 * 1.1515;// 英里
    //    double feet = miles * 5280; // 英尺
    double kilometers = miles * 1.609344; // 千米
    kilometers = kilometers * 1000;
    kilometers = round(kilometers);
    NSString *milsStr = [NSString stringWithFormat:@"%0.f", kilometers];
    return milsStr;
}

#pragma mark - 其他
#pragma mark - 防止nil，如果是nil,返回空字符串
+ (NSString *)avoidNil:(NSString *)str {
    if (!str) return @"";
    if ([str isEqualToString:@"(null)"]) return @"";
    return str;
}

#pragma mark - 检查value是否为空，是空则返回NO,非空返回YES
+ (BOOL)isNotNull:(id)value {
    if (!value) return NO;
    if ([value isKindOfClass:[NSNull class]]) return NO;
    return YES;
}

#pragma mark - 判断字符串是否为空，是非空则返回NO,空返回YES
+ (BOOL)isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

#pragma mark - 判断文件夹是否存在
+ (BOOL)isExistFile:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        return false;
    }
    return true;
}

#pragma mark - 相册权限
+ (BOOL)albumAuthority {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - 相机权限
+ (BOOL)canRecordViedo{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - 去设置是否开启定位
+ (void)gotoSetting {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark - 字符串去前后空格
+ (NSString *)stringGoesBeforeAndAfterTheSpace:(NSString *)string{
    //去空格和回车
    //如果仅仅是去前后空格，用whitespaceCharacterSet
    NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    string = [string stringByTrimmingCharactersInSet:set];
    return string;
}
@end
